#include <fhetext/Window.h>
#include <fhe/core/Registerers.h>
#include <ncurses.h>

namespace fhe
{
  namespace text
  {
    FHE_NODE( fhetext, Window );
    FHE_NODE_INTERFACE( fhetext, Window, core, IUpdatable );
    FHE_VAR( fhetext, Window, frameRate );
    
    Window::Window()
      : frameRate( 50 )
      , lastRender_( -1 )
    {
      initscr();
      cbreak();
      noecho();
      nodelay( stdscr, 1 );
      keypad( stdscr, 1 );
      curs_set( 0 );
    }
    
    Window::~Window()
    {
      curs_set( 1 );
      nocbreak();
      keypad( stdscr, 0 );
      echo();
      endwin();
    }
    
    void Window::update( double t, double dt )
    {
      int w, h;
      char c;
      if ( lastRender_ < 0 || ( t - lastRender_ ) >= 1. / frameRate )
      {
        lastRender_ = t;
        
        c = getch();
        if ( c != ERR )
        {
          if ( c == 27 )
          {
            root()->call( "shutdown" );
          }
          publish( "input", c );
        }
        
        getmaxyx( stdscr, h, w );
        context_.setSize( Vec2i( w, h ) );

        IRenderContext2i* context = &context_;
        publish( "render", context );
        context_.render();
        refresh();
        context_.swap();
      }
    }
  }
}
